package com.xbongbong.pay.platform.unionpay.config;

import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Collections;
import java.util.Map;

/**
 *
 * @author 魏荣杰
 * @date 2021/1/21 10:50
 * @since
 * @version
 */
public class UnionPayConfigCondition extends SpringBootCondition {

    private static final Bindable<Map<String, UnionPayConfig.Config>> MAP_BINDABLE = Bindable.mapOf(String.class, UnionPayConfig.Config.class);


    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        ConditionMessage.Builder message= ConditionMessage.forCondition("Union Pay Configured Condition");
        Map<String, UnionPayConfig.Config> config = getConfig(context.getEnvironment());
        if (!config.isEmpty()) {
            return ConditionOutcome.match("registered union pay size" + config.size());
        }
        return ConditionOutcome.noMatch(message.notAvailable("registered union pay configs"));
    }

    private Map<String, UnionPayConfig.Config> getConfig(Environment environment) {
        return Binder.get(environment).bind("union.pay.config", MAP_BINDABLE).orElse(Collections.emptyMap());
    }
}
